package com.itheima.aop;

import com.itheima.Utils.JwtUtils;
import com.itheima.mapper.OperateLogMapper;
import com.itheima.pojo.OperateLog;
import io.jsonwebtoken.Claims;
import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.Arrays;

@Aspect
@Component
@Slf4j
public class LogAspect {
    @Autowired
    private OperateLogMapper operateLogMapper;
    @Autowired
    private HttpServletRequest httpServletRequest;
    @Around("@annotation(com.itheima.anno.Log)")
    public Object recordLog(ProceedingJoinPoint joinPoint) throws Throwable {
        long start = System.currentTimeMillis();
        //获取请求头的token的jwt令牌，并解析
        Claims claims = JwtUtils.parseJWT(httpServletRequest.getHeader("token"));
        //获取操作此功能的用户的id
        Integer operateEmpId = (Integer)claims.get("id");
        LocalDateTime operateTime = LocalDateTime.now();
        //获取该操作请求的类名、方法名、参数
        String className = joinPoint.getTarget().getClass().getName();
        String methodName = joinPoint.getSignature().getName();
        String methodParams = Arrays.toString(joinPoint.getArgs());
        //调用原始目标方法运行
        Object result = joinPoint.proceed();
        String returnvalue = result.toString();
        long costTime = System.currentTimeMillis() - start;
        //记录日志
        OperateLog operateLog = new OperateLog(null, operateEmpId, operateTime, className, methodName, methodParams, returnvalue, costTime, null);
        operateLogMapper.insert(operateLog);
        log.info("耗时:{}ms",costTime);
        log.info("AOP记录操作日志: {} ", operateLog);
        return result;
    }
}
